<template>
  <div class="learning-analytics">
    <div class="page-header">
      <h1>智能学习分析</h1>
      <p>基于AI技术分析学习数据，提供个性化学习建议</p>
    </div>

    <el-row :gutter="24">
      <!-- 分析配置 -->
      <el-col :span="8">
        <el-card class="analytics-config">
          <template #header>
            <span>分析配置</span>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="分析类型" prop="analysis_type">
              <el-radio-group v-model="form.analysis_type" @change="onAnalysisTypeChange">
                <el-radio-button label="learning_progress">学习进度分析</el-radio-button>
                <el-radio-button label="study_recommendations">学习建议</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="学科" prop="subject">
              <el-select v-model="form.subject" placeholder="请选择学科">
                <el-option label="数学" value="math" />
                <el-option label="语文" value="chinese" />
                <el-option label="英语" value="english" />
                <el-option label="物理" value="physics" />
                <el-option label="化学" value="chemistry" />
                <el-option label="生物" value="biology" />
              </el-select>
            </el-form-item>

            <!-- 学习进度分析配置 -->
            <template v-if="form.analysis_type === 'learning_progress'">
              <el-form-item label="时间范围">
                <el-select v-model="timeRange" placeholder="选择时间范围">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                  <el-option label="全部时间" value="all" />
                </el-select>
              </el-form-item>

              <el-form-item label="数据类型">
                <el-checkbox-group v-model="selectedDataTypes">
                  <el-checkbox label="exam_scores">考试成绩</el-checkbox>
                  <el-checkbox label="practice_records">练习记录</el-checkbox>
                  <el-checkbox label="study_time">学习时长</el-checkbox>
                  <el-checkbox label="question_performance">答题表现</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>

            <!-- 学习建议配置 -->
            <template v-if="form.analysis_type === 'study_recommendations'">
              <el-form-item label="薄弱知识点">
                <el-select
                  v-model="form.weak_areas"
                  multiple
                  placeholder="选择薄弱知识点"
                  style="width: 100%"
                >
                  <el-option
                    v-for="topic in availableTopics"
                    :key="topic.value"
                    :label="topic.label"
                    :value="topic.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建议类型">
                <el-checkbox-group v-model="recommendationTypes">
                  <el-checkbox label="practice">练习题目</el-checkbox>
                  <el-checkbox label="study_materials">学习资料</el-checkbox>
                  <el-checkbox label="learning_path">学习路径</el-checkbox>
                  <el-checkbox label="time_management">时间管理</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>

            <el-form-item>
              <el-button
                type="primary"
                :loading="analyzing"
                @click="startAnalysis"
                :disabled="!canAnalyze"
              >
                <el-icon><DataAnalysis /></el-icon>
                {{ analyzing ? '分析中...' : '开始分析' }}
              </el-button>
              <el-button @click="resetForm">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="loadSampleData">
                <el-icon><Document /></el-icon>
                加载示例
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 快速统计 -->
        <el-card class="quick-stats" style="margin-top: 20px;">
          <template #header>
            <span>学习统计</span>
          </template>

          <el-descriptions :column="1" size="small">
            <el-descriptions-item label="总学习时长">
              {{ formatDuration(stats.total_study_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="完成练习">
              {{ stats.completed_practices }} 题
            </el-descriptions-item>
            <el-descriptions-item label="平均分数">
              {{ stats.average_score }} 分
            </el-descriptions-item>
            <el-descriptions-item label="学习连续天数">
              {{ stats.consecutive_days }} 天
            </el-descriptions-item>
            <el-descriptions-item label="AI分析次数">
              {{ stats.ai_analysis_count }} 次
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 分析结果 -->
      <el-col :span="16">
        <el-card class="analytics-results">
          <template #header>
            <div class="results-header">
              <span>分析结果</span>
              <div class="actions" v-if="analysisResult">
                <el-button
                  type="success"
                  size="small"
                  @click="saveAnalysis"
                >
                  <el-icon><Check /></el-icon>
                  保存分析
                </el-button>
                <el-button
                  size="small"
                  @click="exportAnalysis"
                >
                  <el-icon><Download /></el-icon>
                  导出报告
                </el-button>
                <el-button
                  size="small"
                  @click="shareAnalysis"
                >
                  <el-icon><Share /></el-icon>
                  分享
                </el-button>
              </div>
            </div>
          </template>

          <!-- 加载状态 -->
          <div v-if="analyzing" class="loading-state">
            <el-progress
              :percentage="analysisProgress"
              :status="analysisStatus"
            />
            <p style="text-align: center; margin-top: 20px;">
              {{ analysisStatusText }}
            </p>
          </div>

          <!-- 空状态 -->
          <el-empty
            v-else-if="!analyzing && !analysisResult"
            description="暂无分析结果，请配置参数后开始分析"
          />

          <!-- 分析结果展示 -->
          <div v-else-if="analysisResult" class="result-content">
            <!-- 学习进度分析结果 -->
            <template v-if="form.analysis_type === 'learning_progress'">
              <!-- 进度概览 -->
              <div class="progress-overview">
                <h3>学习进度概览</h3>
                <el-row :gutter="16">
                  <el-col :span="8">
                    <div class="metric-card">
                      <div class="metric-value">{{ analysisResult.progress_rate || 85 }}%</div>
                      <div class="metric-label">整体进度</div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="metric-card">
                      <div class="metric-value">{{ analysisResult.mastered_topics || 12 }}</div>
                      <div class="metric-label">掌握知识点</div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="metric-card">
                      <div class="metric-value">{{ analysisResult.weekly_improvement || 15 }}%</div>
                      <div class="metric-label">周进步率</div>
                    </div>
                  </el-col>
                </el-row>
              </div>

              <!-- 学习趋势图 -->
              <div class="trend-chart">
                <h3>学习趋势</h3>
                <div ref="trendChartRef" style="height: 300px;"></div>
              </div>

              <!-- 知识点掌握情况 -->
              <div class="knowledge-mastery">
                <h3>知识点掌握情况</h3>
                <div class="mastery-list">
                  <div
                    v-for="(topic, index) in knowledgeTopics"
                    :key="index"
                    class="mastery-item"
                  >
                    <div class="topic-info">
                      <span class="topic-name">{{ topic.name }}</span>
                      <el-tag :type="getMasteryType(topic.mastery)" size="small">
                        {{ topic.mastery }}%
                      </el-tag>
                    </div>
                    <el-progress
                      :percentage="topic.mastery"
                      :color="getMasteryColor(topic.mastery)"
                      :stroke-width="6"
                    />
                  </div>
                </div>
              </div>
            </template>

            <!-- 学习建议结果 -->
            <template v-if="form.analysis_type === 'study_recommendations'">
              <!-- 建议概览 -->
              <div class="recommendations-overview">
                <h3>个性化学习建议</h3>
                <el-alert
                  title="AI智能分析结果"
                  type="success"
                  :closable="false"
                  show-icon
                >
                  <template #default>
                    基于您的学习数据和行为模式，AI为您生成了个性化的学习建议，帮助您更高效地提升学习效果。
                  </template>
                </el-alert>
              </div>

              <!-- 优先级建议 -->
              <div class="priority-recommendations">
                <h3>优先改进建议</h3>
                <el-timeline>
                  <el-timeline-item
                    v-for="(recommendation, index) in priorityRecommendations"
                    :key="index"
                    :type="getPriorityType(recommendation.priority)"
                    :icon="getPriorityIcon(recommendation.priority)"
                  >
                    <div class="recommendation-content">
                      <h4>{{ recommendation.title }}</h4>
                      <p>{{ recommendation.description }}</p>
                      <div class="recommendation-meta">
                        <el-tag size="small">{{ recommendation.subject }}</el-tag>
                        <span class="time-estimate">预计时间：{{ recommendation.estimated_time }}</span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>

              <!-- 学习资源推荐 -->
              <div class="resource-recommendations">
                <h3>学习资源推荐</h3>
                <el-row :gutter="16">
                  <el-col
                    v-for="(resource, index) in recommendedResources"
                    :key="index"
                    :span="8"
                  >
                    <el-card class="resource-card" :body-style="{ padding: '16px' }">
                      <div class="resource-icon">
                        <el-icon :size="24">
                          <component :is="getResourceIcon(resource.type)" />
                        </el-icon>
                      </div>
                      <div class="resource-info">
                        <h4>{{ resource.title }}</h4>
                        <p>{{ resource.description }}</p>
                        <div class="resource-meta">
                          <el-tag size="small" type="info">{{ resource.type }}</el-tag>
                          <span class="difficulty">{{ resource.difficulty }}</span>
                        </div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </template>

            <!-- AI洞察 -->
            <div class="ai-insights">
              <h3>
                <el-icon><Lightbulb /></el-icon>
                AI洞察分析
              </h3>
              <div class="insights-content">
                {{ analysisResult.insights || '基于您的学习数据分析，建议重点关注数学函数部分的学习，这是您相对薄弱的环节。同时保持良好的学习节奏，每周安排固定的学习时间。' }}
              </div>
            </div>

            <!-- 行动计划 -->
            <div class="action-plan">
              <h3>
                <el-icon><Calendar /></el-icon>
                行动计划建议
              </h3>
              <el-table :data="actionPlan" style="width: 100%">
                <el-table-column prop="week" label="周次" width="80" />
                <el-table-column prop="goal" label="学习目标" />
                <el-table-column prop="tasks" label="具体任务" />
                <el-table-column prop="time_allocation" label="时间分配" width="120" />
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button size="small" @click="addToCalendar(scope.row)">
                      加入日历
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  DataAnalysis, Refresh, Document, Check, Download, Share,
  Lightbulb, Calendar, VideoReading, Notebook, Reading, Monitor
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { aiApi, type AnalyticsRequest } from '@/api/ai'

// 响应式数据
const analyzing = ref(false)
const analysisProgress = ref(0)
const analysisStatus = ref<'success' | 'exception' | ''>('')
const analysisStatusText = ref('')
const analysisResult = ref<any>(null)
const trendChartRef = ref<HTMLElement>()

// 表单数据
const form = ref<AnalyticsRequest>({
  analysis_type: 'learning_progress',
  subject: '',
  performance_data: [],
  weak_areas: []
})

// 配置数据
const timeRange = ref('30d')
const selectedDataTypes = ref(['exam_scores', 'practice_records'])
const recommendationTypes = ref(['practice', 'study_materials'])

// 统计数据
const stats = ref({
  total_study_time: 7200, // 秒
  completed_practices: 156,
  average_score: 85.5,
  consecutive_days: 12,
  ai_analysis_count: 8
})

// 模拟数据
const knowledgeTopics = ref([
  { name: '函数与方程', mastery: 85 },
  { name: '几何图形', mastery: 72 },
  { name: '概率统计', mastery: 68 },
  { name: '数列', mastery: 90 },
  { name: '三角函数', mastery: 65 }
])

const priorityRecommendations = ref([
  {
    title: '加强函数概念理解',
    description: '函数是数学的基础概念，建议重点复习函数的定义、性质和图像',
    priority: 'high',
    subject: '数学',
    estimated_time: '2小时'
  },
  {
    title: '练习几何证明题',
    description: '通过大量练习提高几何证明的解题能力',
    priority: 'medium',
    subject: '数学',
    estimated_time: '1.5小时'
  },
  {
    title: '复习概率统计基础',
    description: '巩固概率论的基本概念和统计方法',
    priority: 'low',
    subject: '数学',
    estimated_time: '1小时'
  }
])

const recommendedResources = ref([
  {
    title: '函数基础视频教程',
    description: '系统讲解函数的概念、性质和应用',
    type: 'video',
    difficulty: '中等'
  },
  {
    title: '几何证明题集',
    description: '包含各种类型的几何证明题目及解析',
    type: 'document',
    difficulty: '困难'
  },
  {
    title: '在线练习平台',
    description: '互动式数学练习，即时反馈',
    type: 'interactive',
    difficulty: '简单'
  }
])

const actionPlan = ref([
  {
    week: '第1周',
    goal: '函数基础复习',
    tasks: '完成函数概念练习，观看教学视频',
    time_allocation: '3小时'
  },
  {
    week: '第2周',
    goal: '函数图像分析',
    tasks: '练习函数图像绘制和分析',
    time_allocation: '4小时'
  },
  {
    week: '第3周',
    goal: '综合应用',
    tasks: '解决综合性的函数应用题',
    time_allocation: '3小时'
  }
])

const availableTopics = ref([
  { label: '函数与方程', value: 'functions' },
  { label: '几何图形', value: 'geometry' },
  { label: '概率统计', value: 'probability' },
  { label: '数列', value: 'sequences' },
  { label: '三角函数', value: 'trigonometry' }
])

// 表单验证规则
const rules = {
  analysis_type: [
    { required: true, message: '请选择分析类型', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ]
}

// 计算属性
const canAnalyze = computed(() => {
  return form.value.analysis_type && form.value.subject
})

// 方法
const onAnalysisTypeChange = (type: string) => {
  analysisResult.value = null
  // 重置相关字段
  if (type === 'learning_progress') {
    form.value.weak_areas = []
  } else {
    form.value.performance_data = []
  }
}

const startAnalysis = async () => {
  try {
    analyzing.value = true
    analysisProgress.value = 0
    analysisStatus.value = ''
    analysisStatusText.value = '正在收集学习数据...'

    // 模拟分析过程
    await simulateAnalysis()

    const response = await aiApi.analyzeLearning(form.value)

    if (response.success) {
      analysisProgress.value = 100
      analysisStatus.value = 'success'
      analysisStatusText.value = '分析完成'
      analysisResult.value = response
      ElMessage.success('学习分析完成')

      // 渲染图表
      if (form.value.analysis_type === 'learning_progress') {
        await nextTick()
        renderTrendChart()
      }
    } else {
      throw new Error(response.error || '分析失败')
    }
  } catch (error: any) {
    analysisProgress.value = 0
    analysisStatus.value = 'exception'
    analysisStatusText.value = '分析失败'
    ElMessage.error(error.message || '学习分析失败')
  } finally {
    analyzing.value = false
  }
}

const simulateAnalysis = () => {
  return new Promise((resolve) => {
    let progress = 0
    const interval = setInterval(() => {
      progress += 10
      analysisProgress.value = progress

      if (progress === 30) {
        analysisStatusText.value = '正在分析学习模式...'
      } else if (progress === 60) {
        analysisStatusText.value = '正在生成个性化建议...'
      } else if (progress === 90) {
        analysisStatusText.value = '正在优化分析结果...'
      }

      if (progress >= 100) {
        clearInterval(interval)
        resolve(true)
      }
    }, 300)
  })
}

const resetForm = () => {
  form.value = {
    analysis_type: 'learning_progress',
    subject: '',
    performance_data: [],
    weak_areas: []
  }
  analysisResult.value = null
  timeRange.value = '30d'
  selectedDataTypes.value = ['exam_scores', 'practice_records']
  recommendationTypes.value = ['practice', 'study_materials']
}

const loadSampleData = () => {
  if (form.value.analysis_type === 'learning_progress') {
    form.value.performance_data = [
      { date: '2024-01-01', score: 75, study_time: 120 },
      { date: '2024-01-02', score: 78, study_time: 90 },
      { date: '2024-01-03', score: 82, study_time: 150 }
    ]
  } else {
    form.value.weak_areas = ['functions', 'geometry']
  }
}

const renderTrendChart = () => {
  if (!trendChartRef.value) return

  const chart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['学习成绩', '学习时长']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: [
      {
        type: 'value',
        name: '成绩',
        min: 0,
        max: 100
      },
      {
        type: 'value',
        name: '时长(小时)',
        min: 0
      }
    ],
    series: [
      {
        name: '学习成绩',
        type: 'line',
        data: [75, 78, 82, 85, 88, 92],
        smooth: true
      },
      {
        name: '学习时长',
        type: 'bar',
        yAxisIndex: 1,
        data: [20, 25, 22, 28, 30, 35]
      }
    ]
  }

  chart.setOption(option)
}

const saveAnalysis = () => {
  ElMessage.success('分析结果已保存')
}

const exportAnalysis = () => {
  const content = `
学习分析报告
==========================================

分析类型：${form.value.analysis_type}
学科：${form.value.subject}
分析时间：${new Date().toLocaleString()}

${analysisResult.value?.insights || ''}

${form.value.analysis_type === 'study_recommendations' ?
  priorityRecommendations.value.map(r => `- ${r.title}: ${r.description}`).join('\n') :
  '详细分析结果请查看系统报告'}
  `.trim()

  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `学习分析报告_${new Date().toLocaleDateString()}.txt`
  link.click()
  URL.revokeObjectURL(url)
}

const shareAnalysis = () => {
  ElMessage.success('分享链接已复制到剪贴板')
}

const addToCalendar = (row: any) => {
  ElMessage.success(`已添加 "${row.goal}" 到学习日历`)
}

const getMasteryType = (mastery: number) => {
  if (mastery >= 80) return 'success'
  if (mastery >= 60) return 'warning'
  return 'danger'
}

const getMasteryColor = (mastery: number) => {
  if (mastery >= 80) return '#67c23a'
  if (mastery >= 60) return '#e6a23c'
  return '#f56c6c'
}

const getPriorityType = (priority: string) => {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return types[priority] || 'info'
}

const getPriorityIcon = (priority: string) => {
  const icons = {
    high: 'Warning',
    medium: 'InfoFilled',
    low: 'SuccessFilled'
  }
  return icons[priority] || 'InfoFilled'
}

const getResourceIcon = (type: string) => {
  const icons = {
    video: VideoReading,
    document: Reading,
    interactive: Monitor,
    notes: Notebook
  }
  return icons[type] || Document
}

const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}

// 生命周期
onMounted(() => {
  // 加载用户统计数据
})
</script>

<style scoped>
.learning-analytics {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.analytics-config {
  height: fit-content;
}

.quick-stats {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.loading-state {
  padding: 40px 20px;
}

.result-content {
  max-height: 600px;
  overflow-y: auto;
}

.progress-overview {
  margin-bottom: 32px;
}

.progress-overview h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.metric-card {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.metric-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  opacity: 0.9;
}

.trend-chart {
  margin-bottom: 32px;
}

.trend-chart h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.knowledge-mastery {
  margin-bottom: 32px;
}

.knowledge-mastery h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.mastery-item {
  margin-bottom: 16px;
}

.topic-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.topic-name {
  font-weight: 500;
  color: #374151;
}

.recommendations-overview {
  margin-bottom: 32px;
}

.recommendations-overview h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.priority-recommendations {
  margin-bottom: 32px;
}

.priority-recommendations h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.recommendation-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.recommendation-content p {
  margin: 0 0 8px 0;
  color: #6b7280;
  line-height: 1.5;
}

.recommendation-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-estimate {
  font-size: 12px;
  color: #6b7280;
}

.resource-recommendations {
  margin-bottom: 32px;
}

.resource-recommendations h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.resource-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
}

.resource-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.resource-icon {
  text-align: center;
  margin-bottom: 12px;
  color: #3b82f6;
}

.resource-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.resource-info p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.resource-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.difficulty {
  font-size: 12px;
  color: #6b7280;
}

.ai-insights {
  margin-bottom: 32px;
}

.ai-insights h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.insights-content {
  padding: 16px;
  background-color: #f0f9ff;
  border-left: 4px solid #3b82f6;
  border-radius: 6px;
  line-height: 1.6;
  color: #1e40af;
}

.action-plan {
  margin-bottom: 32px;
}

.action-plan h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

@media (max-width: 768px) {
  .learning-analytics {
    padding: 16px;
  }

  .el-col {
    margin-bottom: 16px;
  }

  .actions {
    flex-direction: column;
    width: 100%;
  }

  .metric-card {
    margin-bottom: 16px;
  }
}
</style>